import { RemoveObjectCommand } from '@/three/commands/RemoveObjectCommand';
import { Editor } from '@/three/Editor';

const onDrop = (event: DragEvent) => {
  event.preventDefault();
  if (!Editor.instance) return;
  if (event.dataTransfer) {
    if (event.dataTransfer.types[0] === 'text/plain') return; // Outliner drop
    if (event.dataTransfer.items) {
      Editor.instance.loader.loadItemList(event.dataTransfer.items);
    } else {
      Editor.instance.loader.loadFiles(event.dataTransfer.files);
    }
  }
};

const onDragover = (event: DragEvent) => {
  event.preventDefault();
  if (event.dataTransfer) {
    event.dataTransfer.dropEffect = 'copy';
  }
};

const onkeydown = (event: KeyboardEvent) => {
  const editor = Editor.instance;
  if (editor === undefined) return;
  switch (event.key.toLowerCase()) {
    case 'backspace':
      event.preventDefault(); // prevent browser back
      break;
    // fall-through

    case 'delete': {
      const object = editor.selected;
      if (object === null) return;
      const _parent = object.parent;
      if (_parent !== null) editor.execute(new RemoveObjectCommand(editor, object));
      break;
    }

    case editor.config.getKey('settings/shortcuts/translate'):
      editor.signals.transformModeChanged.dispatch('translate');
      break;

    case editor.config.getKey('settings/shortcuts/rotate'):
      editor.signals.transformModeChanged.dispatch('rotate');
      break;

    case editor.config.getKey('settings/shortcuts/scale'):
      editor.signals.transformModeChanged.dispatch('scale');
      break;

    case editor.config.getKey('settings/shortcuts/undo'):
      if (event.ctrlKey) {
        event.preventDefault(); // Prevent browser specific hotkeys
        editor.undo();
      }
      break;

    case editor.config.getKey('settings/shortcuts/redo'):
      if (event.ctrlKey) {
        event.preventDefault(); // Prevent browser specific hotkeys
        editor.redo();
      }
      break;

    case editor.config.getKey('settings/shortcuts/focus'):
      if (editor.selected !== null) {
        editor.focus(editor.selected);
      }
      break;
  }
};

const onresize = () => {
  if (!Editor.instance) return;
  Editor.instance.signals.windowResize.dispatch();
};

const init = (dom: HTMLElement) => {
  new Editor(dom);
  dom.addEventListener('dragover', onDragover);
  dom.addEventListener('drop', onDrop);
  document.addEventListener('keydown', onkeydown);
  window.addEventListener('resize', onresize);
};

const dispose = (dom: HTMLElement) => {
  dom.removeEventListener('dragover', onDragover);
  dom.removeEventListener('drop', onDrop);
  document.removeEventListener('keydown', onkeydown);
  window.removeEventListener('resize', onresize);
};

export { init, dispose };
